package mn.idax.exchange.otc.util;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import mn.idax.exchange.otc.domain.capital.BalancesDTO;
import mn.idax.exchange.otc.entity.Account;
import mn.idax.exchange.otc.enums.response.SystemStatusResponseEnum;
import mn.idax.exchange.otc.exception.IdaxException;
import okhttp3.*;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Auther: dison
 * @Date: 2018/8/15 18:04
 * @Description: OKhttp工具类
 */
public class OkHttpClientUtils {
    static final int CONN_TIMEOUT = 5;
    static final int READ_TIMEOUT = 5;
    static final int WRITE_TIMEOUT = 5;

    static final MediaType JSONMediaType = MediaType.parse("application/json");

    static final OkHttpClient client = createOkHttpClient();

    public static <T> T get(String url, Map<String, String> params, TypeReference<T> ref) {
        if (params == null) {
            params = new HashMap<>();
        }
        return call("GET", url, null, params, ref);
    }

    public static <T> T post(String url, Object object, TypeReference<T> ref) {
        return call("POST", url, object, new HashMap<String, String>(), ref);
    }

    static OkHttpClient createOkHttpClient() {
        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(CONN_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS).writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                .build();
        client.proxy();
        return client;
    }

    public static <T> T call(String method, String url, Object object, Map<String, String> params,
                             TypeReference<T> ref) {
        try {
            Request.Builder builder = null;
            String requestUrl = getRequestUrl(url, params);
            if ("POST".equals(method)) {
                //add by kwan 2019-01-03
                RequestBody body = null;
                if (object instanceof String) {
                    body = RequestBody.create(JSONMediaType, object.toString());
                } else {
                    body = RequestBody.create(JSONMediaType, JSON.toJSONString(object));
                }
                builder = new Request.Builder().url(requestUrl).post(body);
            } else {
                builder = new Request.Builder().url(requestUrl).get();
            }
            Request request = builder.build();
            Response response = client.newCall(request).execute();
            String s = response.body().string();
            return JsonUtil.readValue(s, ref);
        } catch (Exception e) {
            LogUtils.warn(OkHttpClientUtils.class, "otcresult is"+ ExceptionUtils.getStackTrace(e));
            throw new IdaxException(SystemStatusResponseEnum.SYSTEM_ERROR.getCode());
        }
    }

    public static String getRequestUrl(String url, Map<String, String> params) {
        StringBuffer requestUrl = new StringBuffer();
        requestUrl.append(url);
        if (params != null && !params.isEmpty()) {
            requestUrl.append("?").append(toQueryString(params));
        }
        return requestUrl.toString();
    }

    public static String toQueryString(Map<String, String> params) {
        return String.join("&", params.entrySet().stream().map((entry) -> {
            return entry.getKey();
        }).collect(Collectors.toList()));
    }

    public static <T> T postRawRequest(String url, Object object, TypeReference<T> ref) {

        String json = JSON.toJSONString(object);
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        StringEntity postingString = null;// json传递
        try {
            postingString = new StringEntity(json);

            post.setEntity(postingString);
            post.setHeader("Content-type", "application/json");
            HttpResponse response = httpClient.execute(post);
            String content = EntityUtils.toString(response.getEntity());
            return JsonUtil.readValue(content, ref);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    public static void main(String[] args) {
        BalancesDTO build = BalancesDTO.builder()
                .coinId(1)
                .userId(3)
                .txName("getBalances")
                .txId(2410)
                .guid(181026123456781212L)
                .build();
        // 修改API获取资金
        Map<String, Object> post = OkHttpClientUtils.post("http://47.244.36.18:12701/api/getBalances", build, new TypeReference<Map<String, Object>>() {
        });
        if ("success".equals(post.get("msg").toString())){
            List<Account> aa = (List<Account>) post.get("data");
            System.out.println();
        }

    }

}
